<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of HttpTokenAuth
 *
 * @author Administrator
 */

namespace frontend\auth;

use yii\filters\auth\AuthMethod;
use Yii;
use frontend\library\MT;
use frontend\exception\UserException;

class HttpTokenAuth extends AuthMethod {

    static $allow = array('test', 'logout', 'login', 'uploadform', 'register', 'loginform', 'respond',
        'checkemail', 'checkusername', 'testlogin', 'shareScore', 'shareInvite', 'sharePk', 'privilege', 'activityList',
        'activityArticleView', 'activityGoddess');
    public $action;
    private $tokenParam = "access_token";
    private $tokenValue;
    public function __construct($config = array()) {
        echo 67;
        parent::__construct($config);
    }
    // 重载events() 使得在事件触发时，调用行为中的一些方法
    public function events()
    {
        // 在EVENT_BEFORE_VALIDATE事件触发时，调用成员函数 beforeValidate
        return [
            'wotest' => 'beforeValidate',
        ];
    }

    // 注意beforeValidate 是行为的成员函数，而不是绑定的类的成员函数。
    // 还要注意，这个函数的签名，要满足事件handler的要求。
    public function beforeValidate($event)
    {
        echo '21';
    }
    public function saveToken(\frontend\bean\UserSession $token) {
        $token->setSid(MT::generateRandStr(32))
                ->setExpire(999)
                ->setDateline(MT::getTime())
                ->setActionline(MT::getTime())
        ;
       $this->$tokenValue = $token;
        return \Yii::$container->get('UserSessionDao')->addSession($token);
    }

    public function getToken() {
       
        return $this->tokenValue ;
    }
    
    public function delToken($token){
      
         return \Yii::$container->get('UserSessionDao')->delSession($token);
    }

    public function authenticate($user, $request, $response) {

        $accessToken = $request->get($this->tokenParam);

        if (is_string($accessToken)) {
            $userSession = \Yii::$container->get('UserSessionDao')->getSessionBySid($accessToken);
            if ($userSession) {

                $identity =$user->recoverAuthStatus($userSession['uid']);

                if (!$identity) {
                    throw new UserException(UserException::E_USER_HAS_LOGIN);
                }
              
                $this->tokenValue = $userSession;
                
                return $identity;

//                $userIp = Yii::$app->request->userIP;
//                $now_time = strtotime('now');
//                $last_login_time = $identity->last_login_time;
//                $diff_time = $now_time - strtotime($last_login_time);
                /**
                 * check ip and time
                 */
//                if ($userIp == $identity->last_login_ip) {
//                    if ($diff_time < Yii::$app->params['restapi']['tokenExpire']) {
//                        return $identity;
//                    } else {
//                        throw new UnauthorizedHttpException(Yii::t('yii', 'You are requesting with an expired access token, please request for a new one.'));
//                    }
//                } else {
//                    throw new UnauthorizedHttpException(Yii::t('yii', 'You are requesting with an access token with a different ip address.'));
//                }
            } else {
                throw new UserException(UserException::E_USER_HAS_LOGIN);
            }
        } else {

            //throw new \UnauthorizedHttpException(Yii::t('yii', 'You are requesting with a wrong-formatted access token.'));
            return "pass";
        }
        if ($accessToken !== null) {

            $this->handleFailure($response);
        }

        return null;
    }

}
